from http.server import HTTPServer, SimpleHTTPRequestHandler
import json
import os
from urllib.parse import parse_qs, urlparse
from datetime import datetime

class ShopHandler(SimpleHTTPRequestHandler):
    def do_GET(self):
        print(f"收到GET请求: {self.path}")
        
        # 处理API请求
        if self.path.startswith('/api/'):
            try:
                self.handle_api()
            except Exception as e:
                print(f"处理API请求时发生错误: {e}")
                self.send_error(500, str(e))
        else:
            try:
                # 处理静态文件
                if self.path == '/':
                    self.path = '/index.html'
                super().do_GET()
            except Exception as e:
                print(f"处理静态文件请求时发生错误: {e}")
                self.send_error(404)

    def end_headers(self):
        # 添加CORS头
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        super().end_headers()

    def do_OPTIONS(self):
        # 处理OPTIONS请求，支持CORS预检
        self.send_response(200)
        self.end_headers()

    def do_POST(self):
        # 处理评论提交
        if self.path == '/api/comments':
            self.handle_add_comment()
        else:
            self.send_error(404)

    def handle_api(self):
        # 解析URL
        parsed_path = urlparse(self.path)
        
        # 处理获取评论的请求
        if parsed_path.path == '/api/comments':
            query_params = parse_qs(parsed_path.query)
            product_id = query_params.get('productId', [None])[0]
            
            print(f"收到评论请求，商品ID: {product_id}")
            
            if product_id:
                comments = self.get_comments(str(product_id))  # 确保product_id是字符串
                print(f"找到评论: {comments}")
                self.send_json(comments)
            else:
                print("缺少商品ID参数")
                self.send_error(400, "Missing productId parameter")
        else:
            print(f"未知的API路径: {parsed_path.path}")
            self.send_error(404)

    def handle_add_comment(self):
        # 获取请求内容长度
        content_length = int(self.headers['Content-Length'])
        # 读取请求体
        post_data = self.rfile.read(content_length)
        
        try:
            # 解析JSON数据
            comment_data = json.loads(post_data.decode('utf-8'))
            # 添加评论
            success = self.add_comment(comment_data)
            
            if success:
                self.send_json({"status": "success"})
            else:
                self.send_error(400, "Invalid comment data")
        except json.JSONDecodeError:
            self.send_error(400, "Invalid JSON")
        except Exception as e:
            self.send_error(500, str(e))

    def send_json(self, data):
        # 发送JSON响应
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()
        self.wfile.write(json.dumps(data).encode())

    def get_comments(self, product_id):
        # 从JSON文件读取评论
        try:
            # 使用绝对路径
            current_dir = os.path.dirname(os.path.abspath(__file__))
            comments_file = os.path.join(current_dir, 'data', 'comments.json')
            
            print(f"尝试读取评论文件: {comments_file}")
            
            if not os.path.exists(comments_file):
                print("评论文件不存在")
                return []
                
            with open(comments_file, 'r', encoding='utf-8') as f:
                comments = json.load(f)
                result = comments.get(product_id, [])
                print(f"商品 {product_id} 的评论: {result}")
                return result
        except FileNotFoundError as e:
            print(f"文件未找到错误: {e}")
            return []
        except json.JSONDecodeError as e:
            print(f"JSON解析错误: {e}")
            return []
        except Exception as e:
            print(f"读取评论时发生错误: {e}")
            return []

    def add_comment(self, comment_data):
        print(f"添加评论，数据: {comment_data}")
        
        # 验证必要字段
        required_fields = ['productId', 'userId', 'content', 'rating']
        if not all(field in comment_data for field in required_fields):
            print(f"缺少必要字段，需要: {required_fields}")
            return False

        try:
            # 获取评论文件的绝对路径
            current_dir = os.path.dirname(os.path.abspath(__file__))
            comments_file = os.path.join(current_dir, 'data', 'comments.json')
            
            # 确保comments.json文件存在
            if not os.path.exists(comments_file):
                print(f"创建新的评论文件: {comments_file}")
                with open(comments_file, 'w', encoding='utf-8') as f:
                    json.dump({}, f)

            # 读取现有评论
            print(f"读取评论文件: {comments_file}")
            with open(comments_file, 'r', encoding='utf-8') as f:
                comments = json.load(f)

            product_id = str(comment_data['productId'])
            
            # 确保该商品的评论列表存在
            if product_id not in comments:
                print(f"为商品 {product_id} 创建新的评论列表")
                comments[product_id] = []

            # 创建新评论
            new_comment = {
                'id': int(datetime.now().timestamp() * 1000),  # 使用时间戳作为ID
                'userId': comment_data['userId'],
                'content': comment_data['content'],
                'rating': int(comment_data['rating']),
                'createdAt': datetime.now().isoformat()
            }

            print(f"添加新评论: {new_comment}")

            # 添加新评论到列表开头
            comments[product_id].insert(0, new_comment)

            # 保存更新后的评论
            print("保存更新后的评论文件")
            with open(comments_file, 'w', encoding='utf-8') as f:
                json.dump(comments, f, ensure_ascii=False, indent=4)

            print("评论添加成功")
            return True
        except Exception as e:
            print(f"添加评论时发生错误: {e}")
            import traceback
            traceback.print_exc()
            return False

def run(server_class=HTTPServer, handler_class=ShopHandler, port=8000):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print(f"Starting server on port {port}...")
    httpd.serve_forever()

if __name__ == '__main__':
    run()